package com.cdxy.model.dto.base.redis;

import com.cdxy.enums.redis.IRedisCacheGroup;
import com.cdxy.model.dto.base.redis.obj.NullObject;
import com.cdxy.model.dto.base.redis.service.RedisService;
import com.cdxy.model.dto.base.redis.util.KeyGeneratorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @Author: tangy
 * @Date: 2020/2/21 16:32
 */
@Component
@Slf4j
public class RedisCacheManager {

    private RedisService redisService;

    private KeyGeneratorUtil keyGeneratorUtil;


    public RedisCacheManager(RedisService redisService, KeyGeneratorUtil keyGeneratorUtil) {
        this.redisService = redisService;
        this.keyGeneratorUtil = keyGeneratorUtil;
    }


    public void put(IRedisCacheGroup redisCacheGroup, String key, Object value, int expirationSecond) {
        if (redisCacheGroup != null && StringUtils.isNotBlank(key) && expirationSecond > 0) {
            if (value == null) {
                value = new NullObject();
            }
            redisService.setEX(this.keyGeneratorUtil.generateCacheKey(redisCacheGroup, key), value, expirationSecond);
        } else {
            log.error("参数异常，添加缓存失败,group{},key{}", redisCacheGroup, key);
        }
    }

    public void cover(IRedisCacheGroup redisCacheGroup, String key, Object value) {
        if (redisCacheGroup != null && StringUtils.isNotBlank(key)) {
            if (value == null) {
                value = new NullObject();
            }
            String cacheKey = this.keyGeneratorUtil.generateCacheKey(redisCacheGroup, key);
            if (redisService.get(cacheKey) == null) {
                log.error("原缓存不存在，缓存失败。group:{}, key:{}", redisCacheGroup, key);
            } else {
                Long ttl = this.redisService.queryTtl(cacheKey);
                redisService.set(cacheKey, value);
                redisService.setTtl(cacheKey, ttl.intValue());
            }
        } else {
            log.error("参数异常，添加缓存失败,group{},key{}", redisCacheGroup, key);
        }
    }

    public void delete(IRedisCacheGroup redisCacheGroup, String key) {
        if (redisCacheGroup == null || StringUtils.isBlank(key)) {
            log.error("删除缓存参数异常");
            return;
        }
        redisService.del(this.keyGeneratorUtil.generateCacheKey(redisCacheGroup, key));
    }

    public Object get(IRedisCacheGroup redisCacheGroup, String key) {
        if (redisCacheGroup == null || StringUtils.isBlank(key)) {
            log.error("获取缓存参数异常");
            return null;
        }
        Object result = redisService.get(this.keyGeneratorUtil.generateCacheKey(redisCacheGroup, key));
        return result instanceof NullObject ? null : result;
    }
}
